package com.qiangqiang.resoldhouse.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.qiangqiang.resoldhouse.entity.Agent;
import com.qiangqiang.resoldhouse.entity.User;
import com.qiangqiang.resoldhouse.mapper.UserMapper;
import com.qiangqiang.resoldhouse.util.MD5Util;
import com.qiangqiang.resoldhouse.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;

/**
 * @author : sky
 * @date : 2018/8/13
 * @description :
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    // 生成全局唯一ID
    SnowflakeIdWorker worker = new SnowflakeIdWorker(4, 1);

    /**
     * @param [user]
     * @return void
     * @author sky
     * @date 2018/8/13
     * @describe: 添加一个用户（注册）
     */
    public void addUser(User user) {
        user.setCreateTime(Instant.now().toEpochMilli());
        user.setUpdateTime(Instant.now().toEpochMilli());
        //MD5 对密码加密
        user.setPassword(MD5Util.inputPassToDbPass(user.getPassword()));
        //生成id
        user.setUserId(worker.nextId());
        userMapper.insert(user);
    }

    /**
     * @param [account]
     * @return boolean
     * @author sky
     * @date 2018/8/13
     * @describe: 根据账号查找用户
     */
    public List<User> findUserByAccount(String account) {
        return userMapper.selectList(new EntityWrapper<User>().eq("account", account));
    }

    /**
     * @param [user]
     * @return boolean
     * @author sky
     * @date 2018/8/13
     * @describe: 验证用户密码是否正确
     */
    public boolean validateUserPassword(User user) {
        List<User> list=findUserByAccount(user.getAccount());
        if (list.size()==0){
            return false;
        }
        return MD5Util.inputPassToDbPass(user.getPassword()).equals(list.get(0).getPassword());
    }

    //根据用户id查找用户
    public User findUserById(Long userId){
        User user = userMapper.selectUserById(userId);
        return user;
    }

    //更新用户
    public Boolean updateUser(User user){
        user.setUpdateTime(Instant.now().toEpochMilli());
        return userMapper.updateUserById(user) > 0;
    }
}
